package com.caac.core.config;

import java.util.Map;

import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.Expression;
import org.hibernate.criterion.MatchMode;
import org.springframework.beans.BeanWrapper;
import org.springframework.beans.BeanWrapperImpl;

/**
 * <p>Title: </p>
 * <p>Description: </p>
 * <p>Copyright: Copyright caac 2006</p>
 * <p>Company: caac</p>
 * @author <a href="mailto:project@caac.com.cn">Project Group</a>
 * @version 1.0
 */

public abstract class LikeOperator extends Operator {
    public void init(Object bean, Map aliasMap, Map propMap, DmProperty dp) {
        BeanWrapper bw = new BeanWrapperImpl(bean);
        Object value = bw.getPropertyValue(dp.getChild(0).getName());
        if (value == null || "".equals(value)) {
            return;
        }
        if (dp.getAlias().isHasAlias()) {
            aliasMap.put(dp.getAlias().getParentName(), dp.getAlias().getPrefix());
        }
        propMap.put(dp.getName(), new Object[] {value});
    }

    public Criterion getCriterion(Map propMap, DmProperty dp) {
        Object[] objects = (Object[]) propMap.get(dp.getName());
        if (objects == null) {
            return null;
        }
        return Expression.like(dp.getAlias().getName(),
                               "%" + (String) objects[0] + "%");
    }

    protected abstract MatchMode getMatchMode();
}
